﻿/**********************************************************************************
 * 程序说明：     数据库助手类(复杂型.有参数)
 * 创建日期：     2009.10.20
 * 程序制作：     agui
 * 联系方式：     mailto: 35 4990393@qq.com  
 * ********************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using PlugNT.Safe;

namespace PlugNT.Database.Common.Complex
{
    /// <summary>
    /// 数据库帮助类
    /// </summary>
    public abstract class DbHelper
    {
        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <param name="connection"></param>
        private static void CloseConnection(DbConnection connection)
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Close();
            }
        }

        #region 公用方法


        /// <summary>
        /// 判断是否存在某表的某个字段(Access和Mysql不能用)
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="tableName"></param>
        /// <param name="columnName"></param>
        /// <returns></returns>
        public static bool ExistsColumn(DbInfo dbinfo,string tableName, string columnName)
        {
            string sql = "select count(1) from syscolumns where [id]=object_id('" +  StringHelper.SqlFilter(tableName) + "') and [name]='" + StringHelper.SqlFilter(columnName) + "'";
            object res = GetSingle(dbinfo,sql);
            if (res == null)
            {
                return false;
            }
            return int.Parse(res.ToString()) > 0;
        }

        /// <summary>
        /// 得到最大的列
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="FieldName"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static int GetMaxField(DbInfo dbinfo, string FieldName, string TableName)
        {
            string strsql = "select max(" + StringHelper.SqlFilter(FieldName) + ") from " + StringHelper.SqlFilter(TableName);
            object obj = GetSingle(dbinfo,strsql);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        /// <summary>
        /// 表是否存在(Mysql不能用)
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static bool ExistsTable(DbInfo dbinfo, string TableName)
        {
            string strSql = DbProvider.GetSearchTableSql(dbinfo, TableName);
            return Exists(dbinfo, strSql);
        }

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="strSql"></param>
        /// <returns></returns>
        public static bool Exists(DbInfo dbinfo,string strSql)
        {
            object obj = GetSingle(dbinfo, strSql);
            return (obj == null) ? false : obj.ToString() != "";
        }

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="strSql"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static bool Exists(DbInfo dbinfo,string strSql, params DbParameter[] cmdParms)
        {
            object obj = GetSingle(dbinfo,strSql, cmdParms);
            return (obj == null) ? false : obj.ToString() != "";
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public static object GetSingle(DbInfo dbinfo,string SQLString)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                using (DbCommand cmd = connection.CreateCommand())
                {
                    try
                    {
                        cmd.Connection = connection;
                        cmd.CommandText = SQLString;
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        cmd.Dispose();
                        CloseConnection(connection);

                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (DbException ex)
                    {
                        connection.Close();
                        throw ex;
                    }
                }
                
            }
        }

        /// <summary>
        /// 执行一条计算查询结果语句，返回查询结果（object）。
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static object GetSingle(DbInfo dbinfo,string SQLString, params DbParameter[] cmdParms)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                using (DbCommand cmd = connection.CreateCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        cmd.Dispose();
                        CloseConnection(connection);

                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (DbException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 重置表
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="tabName"></param>
        /// <param name="idName"></param>
        /// <returns></returns>
        public static bool ReSetTable(DbInfo dbinfo, string tabName, string idName)
        {
            ExecuteSql(dbinfo, "delete from " + StringHelper.SqlFilter(tabName));
            return (ExecuteSql(dbinfo, Tables.GetReSetTableStr(dbinfo, tabName, idName))>0)?true:false;
        }
        #endregion

        #region  执行简单SQL语句
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public static int ExecuteSql(DbInfo dbinfo,string SQLString)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                using (DbCommand cmd = connection.CreateCommand())
                {
                    try
                    {
                        cmd.Connection = connection;
                        cmd.CommandText = SQLString;
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Dispose();
                        CloseConnection(connection);
                        return rows;
                    }
                    catch (DbException ex)
                    {
                        connection.Close();
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数(时间限制)
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <param name="Times"></param>
        /// <returns></returns>
        public static int ExecuteSqlByTime(DbInfo dbinfo,string SQLString, int Times)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                using (DbCommand cmd = connection.CreateCommand())
                {
                    try
                    {
                        cmd.Connection = connection;
                        cmd.CommandText = SQLString;
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Dispose();
                        CloseConnection(connection);
                        return rows;
                    }
                    catch (DbException ex)
                    {
                        connection.Close();
                        throw ex;
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLStringList"></param>
        /// <param name="error"></param>
        /// <returns></returns>
	
        public static int ExecuteSqlTran(DbInfo dbinfo,List<String> SQLStringList,out string error)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DbCommand cmd = connection.CreateCommand();
                cmd.Connection = connection;
                connection.Open();
                DbTransaction tx = connection.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    cmd.Dispose();
                    CloseConnection(connection);
                    error = "";
                    return count;

                }
                catch(Exception ex)
                {
                    tx.Rollback();
                    connection.Close();
                    error = ex.Message + "\n" + ex.StackTrace;
                    return 0;
                }
            }
        }
        
        /// <summary>
        /// 执行查询语句，返回DbDataReader ( 注意：调用该方法后，一定要对DbDataReader进行Close )
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public static DbDataReader GetReader(DbInfo dbinfo, string SQLString)
        {
            DbConnection connection = DbProvider.CreateConnection(dbinfo);
            DbCommand cmd = connection.CreateCommand(); 
            try
            {
                cmd.Connection = connection;
                cmd.CommandText = SQLString;
                connection.Open();
                DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
                return myReader;
            }
            catch (DbException ex)
            {
                CloseConnection(connection);
                throw ex;
            }

        }

        /// <summary>
        /// 执行查询语句，返回DataTable
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public static DataTable GetDataTable(DbInfo dbinfo, string SQLString)
        {
            return GetDataSet(dbinfo, SQLString).Tables[0];
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <returns></returns>
        public static DataSet GetDataSet(DbInfo dbinfo, string SQLString)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    DbDataAdapter da = DbProvider.GetFactory(dbinfo).CreateDataAdapter();
                    DbCommand cmd = connection.CreateCommand();
                    cmd.CommandText = SQLString;
                    da.SelectCommand = cmd;
                    da.Fill(ds);
                    cmd.Dispose();
                    CloseConnection(connection);
                }
                catch (DbException ex)
                {
                    connection.Close();
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }
        #endregion

        #region 执行带参数的SQL语句

       

        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static int ExecuteSql(DbInfo dbinfo,string SQLString, params DbParameter[] cmdParms)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                using (DbCommand cmd = connection.CreateCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        cmd.Dispose();
                        CloseConnection(connection);
                        return rows;
                    }
                    catch (DbException e)
                    {
                        CloseConnection(connection);
                        throw e;
                    }
                }
            }
        }


        /// <summary>
        /// 执行查询语句，返回DbDataReader ( 注意：调用该方法后，一定要对DbDataReader进行Close )
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static DbDataReader ExecuteReader(DbInfo dbinfo,string SQLString, params DbParameter[] cmdParms)
        {
            DbConnection connection = DbProvider.CreateConnection(dbinfo);
            DbCommand cmd = connection.CreateCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                DbDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);  //关闭DataReader会自动关闭此连接
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (DbException e)
            {
                CloseConnection(connection);
                throw e;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="SQLString"></param>
        /// <param name="cmdParms"></param>
        /// <returns></returns>
        public static DataSet GetDataSet(DbInfo dbinfo,string SQLString, params DbParameter[] cmdParms)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DbCommand cmd = connection.CreateCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (DbDataAdapter da = DbProvider.GetFactory(dbinfo).CreateDataAdapter())
                {
                    da.SelectCommand = cmd;
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                        CloseConnection(connection);
                    }
                    catch (DbException ex)
                    {
                        CloseConnection(connection);
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }

        /// <summary>
        /// 创建Command
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="conn"></param>
        /// <param name="trans"></param>
        /// <param name="cmdText"></param>
        /// <param name="cmdParms"></param>
        private static void PrepareCommand(DbCommand cmd, DbConnection conn, DbTransaction trans, string cmdText, DbParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                cmd.Transaction = trans;
            }
            cmd.CommandType = CommandType.Text;
            if (cmdParms != null)
            {
                foreach (DbParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&  (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }

        #endregion

        #region 存储过程操作（限于sql server）

        /// <summary>
        /// 执行存储过程，返回DbDataReader ( 注意：调用该方法后，一定要对DbDataReader进行Close )
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static DbDataReader RunProcedure(DbInfo dbinfo,string storedProcName, IDataParameter[] parameters)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DbDataReader returnReader;
                connection.Open();

                DbCommand cmd = BuildQueryCommand(connection, storedProcName, parameters);
                cmd.CommandType = CommandType.StoredProcedure;
                returnReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                return returnReader;
            }
        }


        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public static DataSet RunProcedure(DbInfo dbinfo,string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                DbDataAdapter sqlDA = DbProvider.GetFactory(dbinfo).CreateDataAdapter(); 
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet, tableName);
                CloseConnection(connection);
                return dataSet;
            }
        }

        /// <summary>
        /// 执行存储过程（限定时间）
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        /// <param name="tableName"></param>
        /// <param name="Times"></param>
        /// <returns></returns>
        public static DataSet RunProcedure(DbInfo dbinfo,string storedProcName, IDataParameter[] parameters, string tableName, int Times)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                DbDataAdapter sqlDA = DbProvider.GetFactory(dbinfo).CreateDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.SelectCommand.CommandTimeout = Times;
                sqlDA.Fill(dataSet, tableName);
                CloseConnection(connection);
                return dataSet;
            }
        }


        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private static DbCommand BuildQueryCommand(DbConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            DbCommand cmd = connection.CreateCommand();  // new SqlCommand(storedProcName, connection);
            cmd.CommandText = storedProcName;
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (DbParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
            return cmd;
        }

        /// <summary>
        /// 执行存储过程，返回影响的行数		
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        /// <param name="rowsAffected"></param>
        /// <returns></returns>
        public static int RunProcedure(DbInfo dbinfo,string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (DbConnection connection = DbProvider.CreateConnection(dbinfo))
            {
                int result;
                connection.Open();
                DbCommand cmd = BuildIntCommand(dbinfo,connection, storedProcName, parameters);
                rowsAffected = cmd.ExecuteNonQuery();
                result = (int)cmd.Parameters["ReturnValue"].Value;
                CloseConnection(connection);
                return result;
            }
        }


        /// <summary>
        /// 创建 SqlCommand 对象实例(用来返回一个整数值)
        /// </summary>
        /// <param name="dbinfo"></param>
        /// <param name="connection"></param>
        /// <param name="storedProcName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        private static DbCommand BuildIntCommand(DbInfo dbinfo,DbConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            DbCommand cmd = BuildQueryCommand(connection, storedProcName, parameters);
            DbParameter dbpar = DbProvider.MakeIntParam(dbinfo, "ReturnValue");
            dbpar.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(dbpar);
            return cmd;
        }

        #endregion



    }
}
